using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using UnityEngine;

namespace Gj.Network.IpRouting
{
    /// <summary>
    /// IP路由管理器 - 支持多个独立实例
    /// </summary>
    public class IpRouterManager
    {
        private static IpRouterManager _defaultInstance;
        public static IpRouterManager Default => _defaultInstance ??= new IpRouterManager("Default");

        private IpRouter _ipRouter;
        private int _maxRetries = 3;
        private int _retryDelayMs = 1000;
        private string _instanceName;

        /// <summary>
        /// 创建新的IP路由管理器实例
        /// </summary>
        /// <param name="instanceName">实例名称，用于区分不同的调用方</param>
        public IpRouterManager(string instanceName = "Default")
        {
            _instanceName = instanceName;
            _ipRouter = new IpRouter();
            Debug.Log($"[IpRouterManager] Created instance: {_instanceName}");
        }

        /// <summary>
        /// 添加IP地址到路由列表
        /// </summary>
        public void AddIp(string ip, int port = 80)
        {
            _ipRouter.AddIp(ip, port);
        }

        /// <summary>
        /// 移除IP地址
        /// </summary>
        public void RemoveIp(string ip, int port = 80)
        {
            _ipRouter.RemoveIp(ip, port);
        }

        /// <summary>
        /// 手动检查所有IP延迟
        /// </summary>
        public async Task CheckAllIpLatency()
        {
            await _ipRouter.CheckAllLatencyAsync();
        }

        /// <summary>
        /// 获取所有IP状态
        /// </summary>
        public List<IpRouter.IpInfo> GetAllIpStatus()
        {
            return _ipRouter.GetAllIpStatus();
        }

        /// <summary>
        /// 设置重试参数
        /// </summary>
        public void SetRetryConfig(int maxRetries, int retryDelayMs)
        {
            _maxRetries = maxRetries;
            _retryDelayMs = retryDelayMs;
            Debug.Log($"[IpRouterManager-{_instanceName}] Set retry config - Max retries: {_maxRetries}, Delay: {_retryDelayMs}ms");
        }

        /// <summary>
        /// 获取当前重试配置
        /// </summary>
        public (int maxRetries, int retryDelayMs) GetRetryConfig()
        {
            return (_maxRetries, _retryDelayMs);
        }

        /// <summary>
        /// 清空所有IP并重新初始化
        /// </summary>
        public void ResetIpRouter()
        {
            _ipRouter.ClearAllIps();
            InitializeDefaultIps();
            Debug.Log($"[IpRouterManager-{_instanceName}] IP router reset and reinitialized");
        }

        /// <summary>
        /// 初始化默认IP列表
        /// </summary>
        public void InitializeDefaultIps()
        {
            // 异步检查延迟
            _ = Task.Run(async () => await _ipRouter.CheckAllLatencyAsync());
        }

        /// <summary>
        /// 获取重试配置（供Api使用）
        /// </summary>
        internal int GetMaxRetries() => _maxRetries;

        /// <summary>
        /// 获取重试延迟（供Api使用）
        /// </summary>
        internal int GetRetryDelayMs() => _retryDelayMs;

        /// <summary>
        /// 获取当前最佳IP（供Api使用）
        /// </summary>
        internal IpRouter.IpInfo GetBestIp()
        {
            return _ipRouter.GetBestIp();
        }

        /// <summary>
        /// 重置IP状态（供Api使用）
        /// </summary>
        internal void ResetIpStatus(string ip, int port)
        {
            _ipRouter.ResetIpStatus(ip, port);
        }

        /// <summary>
        /// 标记IP失败（供Api使用）
        /// </summary>
        internal void MarkIpFailed(string ip, int port)
        {
            _ipRouter.MarkIpFailed(ip, port);
        }

        /// <summary>
        /// 检查所有IP延迟（供Api使用）
        /// </summary>
        internal async Task CheckAllLatencyAsync()
        {
            await _ipRouter.CheckAllLatencyAsync();
        }
    }
}

